package com.bkhc.business.repository;


import com.bkhc.business.entity.ApplyRecord;
import com.bkhc.business.entity.BusinessPriceAccount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

public interface BusinessPriceAccountRepository extends JpaRepository<BusinessPriceAccount,String>, JpaSpecificationExecutor<BusinessPriceAccount> {
    default Page<BusinessPriceAccount> findAll(BusinessPriceAccount priceAccount, Pageable pageable){
        return findAll(new Specification<BusinessPriceAccount>() {
            @Override
            public Predicate toPredicate(Root<BusinessPriceAccount> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(priceAccount.getMemberId())){
                    predicate.add(criteriaBuilder.equal(root.get("memberId").as(String.class), priceAccount.getMemberId()));
                }
                if(!StringUtils.isEmpty(priceAccount.getProductCode())){
                    predicate.add(criteriaBuilder.equal(root.get("productCode").as(Integer.class),priceAccount.getProductCode()));
                }
                if(!StringUtils.isEmpty(priceAccount.getIdentities())){
                    predicate.add(criteriaBuilder.equal(root.get("identities").as(Integer.class),priceAccount.getIdentities()));
                }
                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);


    }
    @Query("select Max(m.id) from BusinessPriceAccount  m")
    Integer generateInviteCode();

}
